package cn.tedu.csmall.passport.repo.impl;

import cn.tedu.csmall.passport.pojo.vo.RoleListItemVO;
import cn.tedu.csmall.passport.pojo.vo.RoleStandardVO;
import cn.tedu.csmall.passport.repo.IRoleRedisRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Slf4j
@Repository
public class RoleRedisRepositoryImpl implements IRoleRedisRepository {
    public RoleRedisRepositoryImpl() {
        log.debug("创建处理缓存的数据访问对象：BrandRedisRepositoryImpl");
    }

    @Autowired
    private RedisTemplate<String, Serializable> redisTemplate;

    @Override
    public void save(RoleStandardVO roleStandardVO) {
        log.debug("开始像Redis中存入角色数据");
        String key = ROLE_ITEM_KEY_PREFIX + roleStandardVO.getId();
        redisTemplate.opsForSet().add(ROLE_ITEM_KEYS_KEY,key);
        redisTemplate.opsForValue().set(key,roleStandardVO);
    }

    @Override
    public void save(List<RoleListItemVO> roles) {
        String key = ROLE_LIST_KEY;
        ListOperations<String, Serializable> ops = redisTemplate.opsForList();
        for (RoleListItemVO role : roles) {
            ops.rightPush(key, role);
        }
    }

    @Override
    public Long deleteAll() {
        Set<Serializable> members =
                redisTemplate.opsForSet().members(ROLE_ITEM_KEYS_KEY);
        Set<String> keys =new HashSet<>();
        for (Serializable member : members) {
            keys.add((String) member);
        }
        keys.add(ROLE_LIST_KEY);
        keys.add(ROLE_ITEM_KEY_PREFIX);
        return redisTemplate.delete(keys);
    }

    @Override
    public RoleStandardVO get(Long id) {
        Serializable serializable =
                redisTemplate.opsForValue().get(ROLE_ITEM_KEY_PREFIX+id);
        RoleStandardVO roleStandardVO = null;
        if (serializable != null){
            if (roleStandardVO instanceof Serializable){
                roleStandardVO = (RoleStandardVO) serializable;
            }
        }
        return roleStandardVO;
    }

    @Override
    public List<RoleListItemVO> list() {
        Long start = 0L;
        Long end = -1L;
        return list(start,end);
    }

    @Override
    public List<RoleListItemVO> list(long start, long end) {
        String key = ROLE_LIST_KEY;
        ListOperations<String, Serializable> ops = redisTemplate.opsForList();
        List<Serializable> list = ops.range(key, start, end);
        List<RoleListItemVO> roleListItemVOS = new ArrayList<>();
        for (Serializable item : list) {
            roleListItemVOS.add((RoleListItemVO) item);
        }
        return roleListItemVOS;

    }
}
